package com.polaris.live.ui.game.js

import android.app.Activity
import com.just.agentweb.AgentWeb
import com.polaris.live.common.util.JsonUtils

/**
 * js交互基类
 *
 * @author Created by lucas on 2023/10/24 11:47
 * @since 1.0.0
 */
abstract class AbstractNativeJsBridgeProxy(
    private val activity: Activity,
    private val mAgent: AgentWeb
) {

    /**
     * 给游戏传递config
     */
    open fun setConfig(h5Function: String, params: String) {
        callJs(h5Function, params)
    }

    /**
     * 通知游戏端刷新货币
     */
    open fun walletUpdate(userId: Long) {
        val map = mutableMapOf<String, String>()
        map["userId"] = userId.toString()
        callJs("walletUpdate", JsonUtils.toJson(map))
    }

    /**
     * 通知yomi游戏端刷新货币
     */
    open fun onBalanceUpdate(coins: Long) {
        callJs("onBalanceUpdate", coins.toString())
    }

    private fun callJs(h5Function: String, params: String) {
        if (h5Function.isEmpty()) {
            return
        }

        activity.runOnUiThread {
            mAgent.webCreator.webView.loadUrl(
                String.format(
                    "javascript:%s(%s)",
                    h5Function,
                    params
                )
            )
        }
    }
}